package cn.liutao.order.api;

import cn.liutao.common.entity.LoginUser;
import cn.liutao.common.utils.ServletUtils;
import cn.liutao.common.utils.ValidUtil;
import cn.liutao.order.entity.dto.OrderCreateResultDto;
import cn.liutao.order.entity.param.OrderPayParam;
import cn.liutao.order.entity.vo.OrderVo;
import cn.liutao.order.service.OrderService;
import cn.liutao.websocket.SocketServer;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.groups.Default;
import java.io.IOException;

/**
 * @author liutao
 * @Description 订单支付api
 * @date 2023/11/2 9:28
 * @Version 1.0
 */
@WebServlet("/order/pay")
@Slf4j
public class OrderPayServlet extends HttpServlet {

    private OrderService orderService;


    @Override
    public void init() throws ServletException {
        orderService = OrderService.getInstance();
    }

    /**
     * 订单支付
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        OrderPayParam payParam = ServletUtils.getBodyParam(req, OrderPayParam.class);
        ValidUtil.validated(payParam, Default.class);
        Integer userId = LoginUser.getUserId();

        OrderCreateResultDto resultDto = orderService.orderPay(userId, payParam);

        //支付成功发送消息
        OrderVo orderVo = orderService.selectVoByNo(resultDto.getOrderNo());
        String jsonString = JSONObject.toJSONString(orderVo);
        SocketServer instance = SocketServer.getInstance();
        log.debug("支付完成，进行消息发送,当前连接：{}",instance);
        instance.sendMessage(jsonString);
        ServletUtils.ok(resp,resultDto,"支付成功");
    }
}
